package com.example.demo.web;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.tio.utils.hutool.StrUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.demo.arithmetic.annotation.ResponseHandler;
import com.example.demo.domain.User;
import com.example.demo.domain.dto.FindActiveUserReqDTO;
import com.example.demo.domain.dto.FindActiveUserResqDTO;
import com.example.demo.domain.dto.UserReq;
import com.example.demo.domain.dto.vo.FindActiveUserReqVO;
import com.example.demo.domain.dto.vo.ModelAndFindActiveUserRespVO;
import com.example.demo.service.SmsService;
import com.example.demo.service.UserService;

@RestController
@RequestMapping("/test")
public class TestController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private UserService userService;

    @Resource
    private StringRedisTemplate template;

    @Autowired
    private SmsService smsService;

    //    @Autowired
    //    private TioWebSocketServerBootstrap bootstrap;

    @GetMapping("/hello")
    public User selectByPrimaryKey(@RequestParam("id") Integer id) {
        return userService.findById(id);
    }

    /**
     * 添加接口
     *
     * @param req
     * @return
     */
    @PostMapping("/add")
    public String addOne(@RequestBody UserReq req) {
        User user = new User();
        //		user.setId(2);
        user.setTel(req.getTel());
        user.setEmail(req.getEmail());
        user.setUsername(req.getUsername());
        userService.save(user);
        return "SUCCESS";
    }

    @PostMapping("/findActiveUser")
    public ModelAndFindActiveUserRespVO findActiveUser(@RequestBody FindActiveUserReqVO reqVO) {
        FindActiveUserReqDTO reqDTO = new FindActiveUserReqDTO();
        reqDTO.setUsername(reqVO.getUsername());
        reqDTO.setEmail(reqVO.getEmail());
        reqDTO.setEnabled(1);
        reqDTO.setQq(reqVO.getQq());
        FindActiveUserResqDTO respDTO = userService.findActiveUser(reqDTO);
        ModelAndFindActiveUserRespVO resp = new ModelAndFindActiveUserRespVO();
        if (respDTO.getSuccess()) {
            resp.setUserList(respDTO.getUserList());
            LOGGER.info("Find active user Successfully!, request is {}", reqVO);
            return resp;
        } else {
            LOGGER.error("no active user!");
            return resp;
        }
    }

    /**
     * @return 导出到excel
     */
    @GetMapping("/download")
    public String download(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        // 导出的用户数据
        List<User> users = userService.selectAll();
        // excelwriter对象，写出到文件或者输出流
        ExcelWriter excelWriter = ExcelUtil.getWriter();
        //        excelWriter.merge()
        excelWriter.write(users);
        servletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
        servletResponse.setHeader("Content-Disposition", "attachment;filename=" + "测试excel.xls");
        try {
            ServletOutputStream outputStream = servletResponse.getOutputStream();
            excelWriter.flush(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            excelWriter.close();
        }
        return "";
    }

    @GetMapping("/redis")
    @ResponseHandler
    public String redisTest(@RequestParam String redisValue) {
        BoundValueOperations<String, String> boundValueOps = template.boundValueOps("key");
        boundValueOps.set(redisValue, 5, TimeUnit.SECONDS);
        String value = boundValueOps.get();
        return value;
    }

    @PostMapping("/send")
    @ResponseBody
    public String send(@RequestParam String phone) throws FileNotFoundException {
        //File file = ResourceUtils.getFile("classpath:templates/b_dfd.txt");
        File file = ResourceUtils.getFile("classpath:templates");
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File childFile : files) {
                    System.out.println(childFile.getName());
                }
            }
        }
        return "success";
    }

    @GetMapping("/msg")
    public void pushMessage(String msg) {
        if (StrUtil.isEmpty(msg)) {
            msg = "hello tio websocket spring boot starter";
        }
        //        Tio.sendToAll(bootstrap.getServerGroupContext(), WsResponse.fromText(msg, "utf-8"));
    }

}
